import type {
  BaseQueryFn,
  FetchArgs,
  FetchBaseQueryError,
} from "@reduxjs/toolkit/query"
import { fetchBaseQuery } from "@reduxjs/toolkit/query"
import { Routes } from "@/shared/consts"
import { logout } from "@/app/user/userSlice"
import { baseUrl } from "@/app/consts"
import type { StrapiError } from "@/shared/interfaces"

export const getToken = () => localStorage.getItem("token")

// @ts-expect-error
const customFetchBase: BaseQueryFn<
  string | FetchArgs,
  unknown,
  FetchBaseQueryError
> = async (args, api, extraOptions) => {
  const baseQuery = fetchBaseQuery({
    baseUrl,
    prepareHeaders: headers => {
      const token = getToken()
      if (token) {
        headers.set("Authorization", `Bearer ${token}`)
      }
      return headers
    },
  })

  const token = getToken()
  if (!token) {
    window.location.href = Routes.Auth
    return
  }
  // wait until the mutex is available without locking it
  const result = await baseQuery(args, api, extraOptions)
  if ((result.error?.data as StrapiError)?.error?.status === 403) {
    api.dispatch(logout())
  }

  return result
}

export default customFetchBase
